<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>生成文章 - 单词记忆</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background: linear-gradient(135deg, #e8f4f8 0%, #f0f8fb 100%);
            background-image:
                radial-gradient(circle at 20% 30%, rgba(64, 158, 255, 0.08) 0%, transparent 25%),
                radial-gradient(circle at 80% 70%, rgba(64, 158, 255, 0.08) 0%, transparent 25%);
            background-attachment: fixed;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        .container {
            background-color: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
            padding: 40px 30px;
            max-width: 900px;
            width: 100%;
            text-align: center;
            border: 1px solid rgba(255, 255, 255, 0.8);
        }
        .icon {
            font-size: 80px;
            margin-bottom: 30px;
            display: block;
        }
        h1 {
            color: #2c3e50;
            font-size: 28px;
            margin-bottom: 10px;
        }
        .description {
            color: #606266;
            font-size: 14px;
            margin-bottom: 20px;
        }
        .back-btn {
            padding: 12px 30px;
            background: linear-gradient(90deg, #409eff, #67c2f9);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
        }
        .back-btn:hover {
            background: linear-gradient(90deg, #3088e0, #409eff);
            box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
            transform: translateY(-2px);
        }
        /* 单词选择区 */
        .word-selection {
            margin: 30px 0;
            text-align: left;
        }
        .word-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 10px;
            max-height: 300px;
            overflow-y: auto;
            padding: 15px;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            border-radius: 8px;
            border: 2px solid #e0e6ed;
        }
        .word-checkbox {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            background: white;
            border: 2px solid #e0e6ed;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .word-checkbox:hover {
            border-color: #409eff;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
        }
        .word-checkbox input[type="checkbox"] {
            margin-right: 8px;
            cursor: pointer;
        }
        .word-checkbox.selected {
            background: linear-gradient(135deg, #e6f7ff, #bae7ff);
            border-color: #409eff;
        }
        .selection-info {
            text-align: center;
            margin: 15px 0;
            color: #606266;
            font-size: 14px;
        }
        .selection-info .count {
            color: #409eff;
            font-weight: 600;
            font-size: 16px;
        }
        .generate-btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(90deg, #67c23a, #85ce61);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 20px;
            box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
        }
        .generate-btn:hover:not(:disabled) {
            background: linear-gradient(90deg, #5daf34, #67c23a);
            box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
            transform: translateY(-2px);
        }
        .generate-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            box-shadow: none;
        }
        /* 文章展示区 */
        .article-display {
            margin-top: 30px;
            display: none;
        }
        .article-display.show {
            display: block;
        }
        .article-section {
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #409eff;
        }
        .article-section h3 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 18px;
        }
        .article-content {
            line-height: 1.8;
            color: #2c3e50;
            font-size: 15px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .article-content strong {
            color: #409eff;
            font-weight: 600;
            background: rgba(64, 158, 255, 0.1);
            padding: 2px 4px;
            border-radius: 3px;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #909399;
        }
        .empty-state::before {
            content: '📚';
            display: block;
            font-size: 60px;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #909399;
        }
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(64, 158, 255, 0.2);
            border-top-color: #409eff;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
            margin-right: 10px;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .error-msg {
            color: #f56c6c;
            background: #fef0f0;
            border: 1px solid #fde2e2;
            padding: 12px;
            border-radius: 6px;
            margin-top: 15px;
            display: none;
        }
        .error-msg.show {
            display: block;
        }
    </style>
    <script>
        let learnedWords = [];
        let selectedWords = [];
        
        async function checkLogin() {
            try {
                const response = await fetch('/api/user', { credentials: 'include' });
                if (!response.ok) {
                    window.location.href = '/login.html';
                    return false;
                }
                return true;
            } catch (err) {
                window.location.href = '/login.html';
                return false;
            }
        }
        
        // 加载已学单词列表
        async function loadLearnedWords() {
            const wordGrid = document.getElementById('wordGrid');
            wordGrid.innerHTML = '<div class="loading"><span class="loading-spinner"></span>加载中...</div>';
            
            try {
                const response = await fetch('/api/learned-words-list', {
                    credentials: 'include'
                });
                
                if (!response.ok) {
                    throw new Error('加载失败');
                }
                
                learnedWords = await response.json();
                
                if (learnedWords.length === 0) {
                    wordGrid.innerHTML = '<div class="empty-state">暂无已学单词，去学习一些单词吧！</div>';
                    return;
                }
                
                renderWordGrid();
                
            } catch (err) {
                console.error('加载已学单词失败：', err);
                wordGrid.innerHTML = '<div class="empty-state">加载失败，请重试</div>';
            }
        }
        
        // 渲染单词网格
        function renderWordGrid() {
            const wordGrid = document.getElementById('wordGrid');
            wordGrid.innerHTML = learnedWords.map((word, index) => `
                <label class="word-checkbox" id="word-${index}">
                    <input type="checkbox" value="${word.headWord}" 
                           onchange="toggleWord('${word.headWord}', ${index})">
                    <span>${word.headWord}</span>
                </label>
            `).join('');
            
            updateSelectionInfo();
        }
        
        // 切换单词选择
        function toggleWord(word, index) {
            const checkbox = document.getElementById(`word-${index}`);
            
            if (selectedWords.includes(word)) {
                selectedWords = selectedWords.filter(w => w !== word);
                checkbox.classList.remove('selected');
            } else {
                if (selectedWords.length >= 15) {
                    showError('最多只能选择15个单词！');
                    checkbox.querySelector('input').checked = false;
                    return;
                }
                selectedWords.push(word);
                checkbox.classList.add('selected');
            }
            
            updateSelectionInfo();
        }
        
        // 更新选择信息
        function updateSelectionInfo() {
            const countEl = document.getElementById('selectedCount');
            const generateBtn = document.getElementById('generateBtn');
            
            countEl.textContent = selectedWords.length;
            generateBtn.disabled = selectedWords.length < 5 || selectedWords.length > 15;
        }
        
        // 显示错误信息
        function showError(message) {
            const errorMsg = document.getElementById('errorMsg');
            errorMsg.textContent = message;
            errorMsg.classList.add('show');
            setTimeout(() => {
                errorMsg.classList.remove('show');
            }, 3000);
        }
        
        // 生成文章
        async function generateArticle() {
            if (selectedWords.length < 5 || selectedWords.length > 15) {
                showError('请选择5-15个单词！');
                return;
            }
            
            const generateBtn = document.getElementById('generateBtn');
            const articleDisplay = document.getElementById('articleDisplay');
            
            generateBtn.disabled = true;
            generateBtn.innerHTML = '<span class="loading-spinner"></span>正在生成...';
            articleDisplay.classList.remove('show');
            
            try {
                const response = await fetch('/api/generate-article', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify({ words: selectedWords })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    displayArticle(result.article, result.translation);
                } else {
                    showError(result.message || '生成失败，请重试');
                }
                
            } catch (err) {
                console.error('生成文章失败：', err);
                showError('网络错误，请重试');
            } finally {
                generateBtn.disabled = false;
                generateBtn.textContent = '生成文章';
            }
        }
        
        // 显示文章
        function displayArticle(article, translation) {
            const articleDisplay = document.getElementById('articleDisplay');
            const articleContent = document.getElementById('articleContent');
            const translationContent = document.getElementById('translationContent');
            
            // 处理文章中的**单词**格式，转为<strong>标签
            const formattedArticle = article.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            
            articleContent.innerHTML = formattedArticle;
            translationContent.textContent = translation;
            
            articleDisplay.classList.add('show');
            
            // 滚动到文章位置
            setTimeout(() => {
                articleDisplay.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }, 100);
        }
        
        window.onload = async () => {
            const isLoggedIn = await checkLogin();
            if (isLoggedIn) {
                loadLearnedWords();
            }
        };
    </script>
</head>
<body>
<div class="container">
    <span class="icon">📄</span>
    <h1>生成文章</h1>
    <p class="description">选择5-15个已学单词，生成包含这些单词的英语文章</p>
    
    <div class="word-selection">
        <div class="selection-info">
            已选择 <span class="count" id="selectedCount">0</span> 个单词（需选择5-15个）
        </div>
        <div class="word-grid" id="wordGrid">
            <div class="loading"><span class="loading-spinner"></span>加载中...</div>
        </div>
    </div>
    
    <button class="generate-btn" id="generateBtn" onclick="generateArticle()" disabled>
        生成文章
    </button>
    
    <div class="error-msg" id="errorMsg"></div>
    
    <!-- 文章展示区 -->
    <div class="article-display" id="articleDisplay">
        <div class="article-section">
            <h3>📝 英文文章</h3>
            <div class="article-content" id="articleContent"></div>
        </div>
        <div class="article-section">
            <h3>🇨🇳 中文翻译</h3>
            <div class="article-content" id="translationContent"></div>
        </div>
    </div>
    
    <button class="back-btn" onclick="window.location.href='/home.html'">返回首页</button>
</div>
</body>
</html>
